﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif

[DisallowMultipleComponent]
[RequireComponent(typeof(Image))]
public class MoreGameButton : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IPointerClickHandler {
	#if UNITY_EDITOR
	[Header("<<Debug>>")]
	[SerializeField]
	protected internal string debugServiceUrl="https://services.cooltweens.net";
	[SerializeField]
	protected internal string debugBundleID="net.cooltweens.facepaintparty2";
	#endif

	[Header("<<Setting>>")]
	//small icon
	[SerializeField]
	protected internal bool isSmall = false;
	//保留banner广告位置
	[SerializeField]
	protected internal bool retainBannerHeight = true;
	//sound
	[SerializeField]
	protected internal AudioClip clickSound;
	//mask material
	[SerializeField]
	protected internal Material material;
	[SerializeField]
	protected internal Vector2 offset ;
	//events
	[Header("<<Events>>")]
	[SerializeField]
	protected internal bool m_ShowEvents=false;
	public UnityEvent OnMoreGameAppear,OnMoreGameDisappear,OnMouseDown,OnMouseUp,OnMouseClick;

	private Image m_Image;
	private Image m_childImage;
	private int m_iconIndex;




	#if UNITY_EDITOR //debug
	private AppClass m_AppClass;

	[System.Serializable]
	public class AppIcon{
		public string icon=null;
	}
	[System.Serializable]
	public class AppClass{
		public string btn_img=null;
		public string secondary_btn_img=null;
		public string default_app_icon=null;
		public List<AppIcon> apps;
	}
	IEnumerator DebugLoad(){
		if(!string.IsNullOrEmpty(debugServiceUrl) && !string.IsNullOrEmpty(debugBundleID)){
			string url = debugServiceUrl+"/more/"+debugBundleID.Substring(debugBundleID.LastIndexOf(".")+1)+"?bundleID="+debugBundleID+"&v=2&top=";
			WWW www = new WWW(url);
			yield return www;
			if(www.isDone && string.IsNullOrEmpty(www.error)){
				m_AppClass = JsonUtility.FromJson<AppClass>(www.text);
				DebugUpdateButtonTexture();
				if(!isSmall){
					StartCoroutine(DebugChangeIcons());
				}
			}
		}
	}
	void DebugUpdateButtonTexture()
	{
		if (isSmall) {
			string smallPath = m_AppClass.secondary_btn_img;
			if (string.IsNullOrEmpty(smallPath)) return;
			StartCoroutine(LoadAndReplaceImage (smallPath, m_Image,delegate() {
				m_Image.raycastTarget = true;
				m_Image.color = Color.white;
			}));
		} else {
			string buttonImagePath = m_AppClass.btn_img;
			if (string.IsNullOrEmpty(buttonImagePath)) return;
			StartCoroutine(LoadAndReplaceImage(buttonImagePath, m_Image, ()=>{
				if(m_Image.sprite) {
					m_Image.color = Color.white;
					m_Image.raycastTarget = true;
				}
			}));
		}
	}
	IEnumerator DebugChangeIcons() 
	{
		if (m_AppClass!=null && m_AppClass.apps!=null && m_AppClass.apps.Count>0){
			if (m_iconIndex >= m_AppClass.apps.Count)
				m_iconIndex = 0;

			string appIconPath = m_AppClass.apps [m_iconIndex].icon;
			if(m_childImage.sprite!=null){
				m_childImage.CrossFadeAlpha(0f,0.3f,false);
				yield return new WaitForSeconds(0.3f);
			}
			StartCoroutine(LoadAndReplaceImage(appIconPath,m_childImage, ()=>{
				if(m_childImage.sprite) {
					m_childImage.color = Color.white;
					m_childImage.CrossFadeAlpha(1f,0.3f,false);
				}
			}));
			++m_iconIndex;
			yield return new WaitForSeconds(6f);
			StartCoroutine(DebugChangeIcons());
		}
	}
	#endif






	void Start () 
	{
		PluginManager.Instance.moreGame.setGameObjectNameForMGM (gameObject.name);
		PluginManager.Instance.moreGame.refresh ();
		m_Image = GetComponent<Image>();
		m_Image.raycastTarget = false;
		m_Image.color = new Color(1f,1f,1f,0f);

		if(!isSmall){
			m_Image.rectTransform.anchorMin = new Vector2(1f,0f);
			m_Image.rectTransform.anchorMax = new Vector2(1f,0f);
			if(retainBannerHeight){
				m_Image.rectTransform.anchoredPosition = new Vector2(-60f,160f)+offset;
			}else{
				m_Image.rectTransform.anchoredPosition = new Vector2(-60f,55f)+offset;
			}
			GameObject child = new GameObject("Icon");
			m_childImage = child.AddComponent<Image>();
			child.transform.SetParent(m_Image.transform);
			m_childImage.raycastTarget = false;
			m_childImage.color = m_Image.color;
			m_childImage.material=material;
			m_childImage.transform.localScale = Vector3.one;
			m_childImage.transform.localPosition = Vector3.zero;
			(child.transform as RectTransform).anchoredPosition=new Vector2(0f,17f);
		}

		#if UNITY_EDITOR
		StartCoroutine(DebugLoad());
		#endif
	}

	#region IMoreGameInterface implementation
	void OnMoreGameDownloadImagesFinished (string message)
	{
		UpdateButtonTexture ();
		if(!isSmall){
			StopCoroutine(ChangeIcons());
			StartCoroutine(ChangeIcons());
		}
	}
	void OnMoreGameDidAppear(string message){
		OnMoreGameAppear.Invoke();
	}
	void OnMoreGameDidDisappear(string message){
		OnMoreGameDisappear.Invoke();
	}
	#endregion


	#region MouseEvent

	public void OnPointerDown (PointerEventData eventData){
		if(m_Image.sprite){
			m_Image.color = Color.gray;
			OnMouseDown.Invoke();
		}
	}
	public void OnPointerUp (PointerEventData eventData){
		if(m_Image.sprite){
			m_Image.color = Color.white;
			OnMouseUp.Invoke();
		}
	}
	public void OnPointerClick (PointerEventData eventData){
		if(m_Image.sprite)
		{
			if(clickSound && Camera.main){
				AudioSource.PlayClipAtPoint(clickSound,Camera.main.transform.position);
			}
			OnMouseClick.Invoke();
			PluginManager.Instance.moreGame.show ();
			#if UNITY_EDITOR
			string url = debugServiceUrl+"/more/"+debugBundleID.Substring(debugBundleID.LastIndexOf(".")+1)+"?bundleID="+debugBundleID+"&v=2";
			Application.OpenURL(url);
			#endif
		}
	}
	#endregion

	void UpdateButtonTexture()
	{
		if (isSmall) {
			string smallPath = PluginManager.Instance.moreGame.getSmallButtonImagePath ();
			if (string.IsNullOrEmpty(smallPath)) return;
				
			smallPath = "file://" + smallPath.Replace ("//", "/");
			StartCoroutine(LoadAndReplaceImage (smallPath, m_Image,delegate() {
				m_Image.raycastTarget = true;
				m_Image.color = Color.white;
			}));
		} else {
			string buttonImagePath = PluginManager.Instance.moreGame.getButtonImagePath ();
			if (string.IsNullOrEmpty(buttonImagePath)) return;

			StartCoroutine(LoadAndReplaceImage(buttonImagePath, m_Image, ()=>{
				if(m_Image.sprite) {
					m_Image.raycastTarget = true;
					m_Image.color = Color.white;
				}
			}));
		}
	}

	IEnumerator ChangeIcons() 
	{
		List<string> icons = PluginManager.Instance.moreGame.getIconsPath ();
		if(icons!=null && icons.Count>0)
		{
			if (m_iconIndex >= icons.Count)
				m_iconIndex = 0;
			string appIconPath = icons [m_iconIndex];
			if (string.IsNullOrEmpty(appIconPath)){
				appIconPath = PluginManager.Instance.moreGame.getFirstAppIconPath ();
			}
			if (m_Image.sprite == null) {
				string buttonImagePath = PluginManager.Instance.moreGame.getButtonImagePath ();
				if (buttonImagePath.Length != 0) {
					buttonImagePath = "file://" + buttonImagePath.Replace ("//", "/");
					StartCoroutine (LoadAndReplaceImage (buttonImagePath, m_Image, () => {
						if(m_Image.sprite) {
							m_Image.raycastTarget = true;
							m_Image.color = Color.white;
						}
					}));
				}
			}

			if(m_Image.sprite!=null){
				m_childImage.CrossFadeAlpha(0f,0.3f,true);
				yield return new WaitForSeconds(0.3f);
			}
			StartCoroutine(LoadAndReplaceImage( "file://" + appIconPath,m_childImage, ()=>{
				if(m_childImage.sprite) {
					m_childImage.color = Color.white;
					m_childImage.CrossFadeAlpha(1f,0.3f,true);
				}
			}));
			++m_iconIndex;
			yield return new WaitForSeconds(6f);
			StartCoroutine(ChangeIcons());
		}
	}

	IEnumerator LoadAndReplaceImage(string url,Image sr, System.Action callBack=null){
		WWW www = new WWW(url);
		yield return www;
		if(www.isDone && www.error == null){
			Texture2D t = www.textureNonReadable;
			if (t != null)
			{
				if(sr.sprite && sr.sprite.texture){
					DestroyImmediate(sr.sprite.texture,false);
					DestroyImmediate(sr.sprite,false);
				}
				sr.sprite = Sprite.Create( t,new Rect(0,0, t.width, t.height),Vector2.one*0.5f,100f,0,SpriteMeshType.FullRect);
				sr.SetNativeSize();
				sr.rectTransform.sizeDelta = sr.rectTransform.sizeDelta/2f;
			}
		}
		www.Dispose();
		if(callBack!=null) callBack();
	}

	void OnDestroy(){
		StopAllCoroutines();
		if(m_Image && m_Image.sprite){
			DestroyImmediate(m_Image.sprite.texture,false);
			DestroyImmediate(m_Image.sprite,false);
		}
		if(m_childImage && m_childImage.sprite){
			DestroyImmediate(m_childImage.sprite.texture,false);
			DestroyImmediate(m_childImage.sprite,false);
		}
	}
}


#if UNITY_EDITOR
[CustomEditor(typeof(MoreGameButton))]
class MoreGameButtonEditor:Editor
{
	public override void OnInspectorGUI ()
	{
		MoreGameButton mgb = target as MoreGameButton;
		serializedObject.Update();
		EditorGUILayout.PropertyField(serializedObject.FindProperty("debugServiceUrl"), true);
		EditorGUILayout.PropertyField(serializedObject.FindProperty("debugBundleID"), true);

		EditorGUILayout.PropertyField(serializedObject.FindProperty("isSmall"), true);
		if(!mgb.isSmall){
			EditorGUILayout.PropertyField(serializedObject.FindProperty("retainBannerHeight"), true);
			EditorGUILayout.PropertyField(serializedObject.FindProperty("material"), true);
			EditorGUILayout.PropertyField(serializedObject.FindProperty("offset"), true);
		}
		EditorGUILayout.PropertyField(serializedObject.FindProperty("clickSound"), true);

		EditorGUILayout.PropertyField(serializedObject.FindProperty("m_ShowEvents"), true);
		if(mgb.m_ShowEvents){
			EditorGUILayout.PropertyField(serializedObject.FindProperty("OnMoreGameAppear"), true);
			EditorGUILayout.PropertyField(serializedObject.FindProperty("OnMoreGameDisappear"), true);
			EditorGUILayout.PropertyField(serializedObject.FindProperty("OnMouseDown"), true);
			EditorGUILayout.PropertyField(serializedObject.FindProperty("OnMouseUp"), true);
			EditorGUILayout.PropertyField(serializedObject.FindProperty("OnMouseClick"), true);
		}
		serializedObject.ApplyModifiedProperties();
	}
}
#endif